import markdown
from weasyprint import HTML
import os
import traceback
from md2pdf.core import md2pdf

directory_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
basepath = os.path.join(directory_path, 'final_output/')
print(basepath)

# 检查目录是否存在，如果不存在则创建
if not os.path.exists(basepath):
    os.makedirs(basepath)

def markdown_to_pdf(input_file, output_file):
    try:
        # 读取 Markdown 文件
        # md2pdf不支持中文
        with open(input_file, 'r') as f:
            markdown_text = f.read()
        # 将 Markdown 转换为 HTML
        html = markdown.markdown(markdown_text)
        html_with_font = f'<style>body {{ font-family: SimSun, sans-serif; }}</style>{html}'

        # # 使用 WeasyPrint 将 HTML 转换为 PDF
        html_obj = HTML(string=html_with_font)
        # html_obj.write_pdf(output_file)

        with open(output_file, 'w', encoding='utf-8') as file:
            file.write(html)



        print(f"成功将 {input_file} 转换为 {output_file}")
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
        traceback.print_exc()

# 示例调用
# input_markdown_file = os.path.join(basepath, 'test3.md')
input_markdown_file = os.path.join(basepath, 'report.md')
output_pdf_file = os.path.join(basepath, 'report2.pdf')
output_html_file = os.path.join(basepath, 'report2.html')
markdown_to_pdf(input_markdown_file, output_html_file)